<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryGoodsList" :inline="true" label-width="68px">
        <el-form-item label="商品名称">
          <el-select v-model="queryGoodsList.materialName" placeholder="请选择物料信息" clearable :style="{ width: '100%' }"
            remote :remote-method="searchSelectNccMaterial" filterable :loading="loading">
            <el-option v-for="item in materialNameOptions" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-switch v-model="queryGoodsList.modeCode" active-text="按编码" inactive-text="按名称" :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
<!--        <el-form-item label="商品状态" prop="skuState">
          <el-select v-model="queryGoodsList.skuState" placeholder="请选择商品状态" clearable :style="{ width: '100%' }"
            @change="verifyOrgChange">
            <el-option v-for="item in stateList" :label="item.VNAME" :value="item.PK_STORESTATE"
              :key="item.PK_STORESTATE" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="仓库">
          <el-select v-model="queryGoodsList.wareHouseID" placeholder="请选择仓库" clearable :style="{ width: '100%' }"
            remote filterable multiple @change="getWareHouse">
            <el-option v-for="item in warehousesList" :label="item.cwarehouse_name" :value="item.cwarehouse_id"
              :key="item.cwarehouse_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="批号" required>
          <el-input v-model="queryGoodsList.node" placeholder="请输入商品批号" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              {{ btnTXT }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="0">全部</el-dropdown-item>
              <el-dropdown-item command="1">等于</el-dropdown-item>
              <el-dropdown-item command="2">不等于</el-dropdown-item>
              <el-dropdown-item command="3">包含</el-dropdown-item>
              <el-dropdown-item command="4">不包含</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" v-hasPermi="['organize:goodsOrg:query']"
            @click="getGoodsQuery">查询</el-button>
          <el-button type="danger" icon="el-icon-refresh" @click="clearAll">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table :data="fenyeList" border height="605px" id="data-table" :default-sort = "{prop: 'date', order: 'descending'}">
        <el-table-column prop="code" label="商品编码" align="center" sortable width="100"></el-table-column>
        <el-table-column prop="vbatchcode" label="批号" sortable align="center"></el-table-column>
        <el-table-column prop="vvendbatchcode" label="供应商批号" align="center"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="materialspec" label="商品规格" align="center"></el-table-column>
        <el-table-column prop="cwarehouse_name" label="仓库名称" align="center"></el-table-column>
        <el-table-column prop="sto_unit_id" label="货位号" align="center"></el-table-column>
        <el-table-column prop="product_name" label="生产厂商" align="center"></el-table-column>
        <el-table-column prop="pd_date" label="生产日期" align="center">
          <template #default="{ row }">
            {{ row.pd_date && row.pd_date !== "1900-01-01 00:00:00" ? formatDate(row.pd_date) : "" }}</template>
        </el-table-column>
        <el-table-column prop="exp_date" label="有效期" align="center">
          <template #default="{ row }">
            <!-- 仅当复验期无效或为空时，才显示有效期 -->
            {{ (!row.retest_date || row.retest_date === "1900-01-01 00:00:00")&&(row.exp_date && row.exp_date !== "1900-01-01 00:00:00") ? formatDate(row.exp_date) : "" }}
          </template>
        </el-table-column>

        <el-table-column prop="retest_date" label="复验期" align="center">
          <template #default="{ row }">
            <!-- 仅当复验期有效时才显示 -->
            {{ row.retest_date && row.retest_date !== "1900-01-01 00:00:00" ? formatDate(row.retest_date) : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="ExpUpdateTime" label="最新效期修改日期" align="center">
          <template #default="{ row }">{{ formatDate(row.ExpUpdateTime) }}</template>
        </el-table-column>
        <el-table-column prop="ResetUpdateTime" label="最新复验期修改日期" align="center" width="90">
          <template #default="{ row }">{{ formatDate(row.ResetUpdateTime) }}</template>
        </el-table-column>
        <el-table-column prop="FreezeUpdateTime" label="最新冻结/解冻日期" align="center">
          <template #default="{ row }">{{ formatDate(row.FreezeUpdateTime) }}</template>
        </el-table-column>
        <el-table-column prop="StateUpdateTime" label="最新状态修改日期" align="center">
          <template #default="{ row }">{{ formatDate(row.StateUpdateTime) }}</template>
        </el-table-column>
        <el-table-column prop="freeze_num" label="冻结数量" align="center"></el-table-column>
        <el-table-column label="主数量" min-width="260">
          <template #default="{ row }">
            <el-descriptions size="mini">
              <el-descriptions-item v-for="item in filteredNumItems(row)" :key="item.key">
                <template slot="label">
                  <span class="label-text">{{ item.label }}</span>
                </template>
                {{ row[item.key] }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column prop="cunit_name" label="单位" align="center"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230">
          <template slot-scope="scope">
            <el-button v-hasPermi="['organize:goodsOrg:edit']" size="mini" type="text" icon="el-icon-edit"
              @click="editFrozen(scope.row)">修改</el-button>
            <el-button v-show="scope.row.sku_no_state_num == 0" v-hasPermi="['organize:goodsOrg:frozen']" size="mini"
              type="text" icon="el-icon-set-up" @click="stateBtn(scope.row)">状态</el-button>
            <el-button v-hasPermi="['organize:goodsOrg:frozen']" size="mini" type="text" icon="el-icon-odometer"
              @click="frozen(scope.row)">冻结</el-button>
            <el-button v-hasPermi="['organize:goodsOrg:frozen']" size="mini" type="text" icon="el-icon-timer"
              @click="queryFrozen(scope.row)">查看&解冻</el-button>
            <el-button v-hasPermi="['organize:goodsOrg:edit']" size="mini" type="text" icon="el-icon-printer"
              @click="printCode(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout=" total,prev, pager, next, sizes,jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize" :page-sizes="[20, 50, 100]"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 解冻&明细 -->
    <queryTable ref="queryVisibleRef" :visible.sync="queryVisible" @successfun="getGoodsQuery"></queryTable>
    <!-- 修改状态 -->
    <frozenDialog ref="frozenDialogRef" :visible.sync="frozenDialogVisible" @successfun="getGoodsQuery"></frozenDialog>
    <!-- 冻结操作 -->
    <frozenOperation ref="frozenOperationRef" :visible.sync="visibleForzen" @successfun="getGoodsQuery">
    </frozenOperation>
    <!-- 修改复验期 -->
    <storeFrozenEdit ref="editFrozenRef" :visible.sync="visible" @successfun="getGoodsQuery"></storeFrozenEdit>
    <!-- 补打 -->
    <goodsPrint v-show="false" ref="buyIndexRef"></goodsPrint>
    <el-dialog :visible.sync="dialogVisible" width="50%" @close="handleClose" title="补打标签" :close-on-click-modal="false" :close-on-press-escape="false">
      <!-- 这里可以放置对话框内部的内容 -->
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" size="medium" label-width="120px" :rules="rules">
          <el-col :span="12">
            <el-form-item label="容器号" prop="sortNum">
              <el-input v-model="formData.sortNum" placeholder="请输入容器号" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打印模式" prop="printMode">
              <el-select v-model="formData.printMode" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in printModel" :key="index" :label="item.name"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板选择" prop="temp">
              <el-select v-model="formData.temp" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in tempList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料代码映射" prop="finallyCode">
              <el-radio-group v-model="formData.finallyCode">
                <el-radio label="1">供应商代码</el-radio>
                <el-radio label="2">GMP码</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div style="color: red;height: 36px;line-height: 36px;">*操作提示：补打则容器号输入如:001,批量补打则输入如:001-003,大码随补打小码自动带出</div>
          </el-col>
          <el-col :span="24" style=" display: flex; justify-content: flex-end;">
            <el-form-item size="large">
              <el-button type="primary" @click="submitPrint">打印</el-button>
              <el-button @click="handleClose">取消</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getWarehouseBasic, //获取商品和仓库下拉
    getWarehouseStatistic, //获取table
    getBillStatusAll //商品状态下拉
  } from "@/api/report/index.js";
  // 获取NCC物料信息-pk  ---头部下拉框
  import {
    getSelectNccMaterialInfo
  } from '@/api/dropDown.js'
  import {
    skuQueryExportData
  } from '@/api/storeM/index.js'
  import storeFrozenEdit from './components/storeFrozenEdit.vue'
  import frozenOperation from './components/frozenOperation.vue' //修改状态
  import frozenDialog from './components/frozenDialog.vue' //冻结
  import queryTable from './components/queryTable.vue' //明细&解冻
  import goodsPrint from '@/views/basic/print/printList/print.vue' //打印
  export default {
    data() {
      return {
        queryGoodsList: {
          materialName: '',
          node: '',
          skuStateValue: 0,
          wareHouseID: [],
          wareHouseValue:0,
          modeCode:0,//0是名称，1是编码
        },
        materialNameOptions: [], // 存储搜索的物料信息
        goodsList: [],
        btnTXT: '等于',
        batchNoMode: 1,
        loading: false,
        pageNum: 1,
        pageSize: 20,
        total: 0,
        stateList: [], //商品类型
        visible: false, //修改按钮
        visibleForzen: false, //修改状态
        frozenDialogVisible: false, //冻结
        queryVisible: false, //冻结
        warehousesList:[],
        formData: {
          sortNum: '',
          printMode: '',
          finallyCode: '',
          temp: '', //模板选择
        },
        printModel: [{
          name: '补打',
          value: '2'
        }], //打印模式
        rules: {
          sortNum: [{
            required: true,
            message: '请输入容器号',
            trigger: 'blur'
          }],
          printMode: [{
            required: true,
            message: '请选择打印模式',
            trigger: 'blur'
          }],
          finallyCode: [{
            required: true,
            message: '映射不能为空',
            trigger: 'change',
          }],
          temp: [{
            required: true,
            message: '模板不能为空',
            trigger: 'change',
          }]
        },
        dialogVisible: false, //打印弹框\
        tempList: [{
          value: 'commercialize',
          label: '物料标签(商业化物料)',
        }, {
          value: 'noCommercialize1',
          label: '物料标签(非商业化第1类)',
        }, {
          value: 'noCommercialize2',
          label: '物料标签(非商业化第2类)',
        }, {
          value: 'psyCommercialize',
          label: '物料精神药品标签(商业化)',
        }, {
          value: 'verification',
          label: '物料精神药品标签(验证阶段)',
        }, {
          value: 'experimental',
          label: '物料精神药品标签(试验开发阶段)',
        }, {
          value: 'boffin',
          label: '物料标签(研究院)',
        }, {
          value: 'productBiaoQ',
          label: '低耗备件标签'
        }, {
          value: 'sampleInstitute',
          label: '样品标签(研究院)',
        }, {
          value: 'productSample1',
          label: '精神商业化产品标签',
        }, {
          value: 'productSample2',
          label: '精神验证阶段产品标签',
        }, {
          value: 'productSample3',
          label: '精神试用开发产品标签',
        }, {
          value: 'productSample',
          label: '中间产品',
        }, {
          value: 'productSampleNew',
          label: '非商业化产品标签',
        }, {
          value: 'importantTip',
          label: '试剂/关键耗材标签'
        }], //模板选择
        numItems: [{
            key: 'unqualified_num',
            label: '不合格'
          },
          {
            key: 'quarantine_num',
            label: '待检'
          },
          {
            key: 'qualified_num',
            label: '合格'
          },
          {
            key: 'limit_eligibility_num',
            label: '限制合格'
          },
          {
            key: 'sku_no_state_num',
            label: '无库存状态'
          },
          {
            key: 'research_num',
            label: '研究用'
          },
          {
            key: 'qualified_no_use_num',
            label: '合格(不上市)'
          },
          {
            key: 'pending_num',
            label: '待处理'
          }
        ]
      }
    },
    components: {
      storeFrozenEdit,
      frozenOperation,
      frozenDialog,
      queryTable,
      goodsPrint
    },
    computed: {
      // 根据当前页码和每页条数计算当前页的数据
      fenyeList() {
        const startIndex = (this.pageNum - 1) * this.pageSize;
        return this.goodsList.slice(startIndex, startIndex + this.pageSize);
      },
      filteredNumItems() {
        return (row) => {
          return this.numItems.filter((item) => row[item.key] > 0);
        };
      }

    },
    created() {
      this.getGoods();
      this.getGoodsState(); //获取下拉商品类型
      this.getData();//仓库下拉
    },
    methods: {
      //切换仓库
      getWareHouse(val) {
        this.queryGoodsList.wareHouseID = val;
        this.queryGoodsList.wareHouseValue = val.length === 0 ? 0 : 1;
        this.getGoodsQuery();
      },
      //获取仓库下拉
      getData() {
        getWarehouseBasic().then(res => {
          this.warehousesList = res.data.type1 || [];
        }).catch(error => {
          this.$message.error('获取仓库数据失败:', error);
        });
      },
      //补打标签
      printCode(row) {
        this.dialogVisible = true;
        this.formData = {
          batchCode: row.pk_batchcode, //批次号
          skuUnit: row.cunit_name, //单位
          pkMaterial: row.pk_material, //商品PK
          skuName: row.name, //商品名
          resetDate: row.retest_date, //复验期
          productionDate: row.pd_date, //生产时间
          skuState: row.sku_state, //商品状态
          vbillcode: row.vbillcode, //单号
          vbatchCode: row.vbatchcode, //批号
          expirationDate: row.exp_date, //有效期
          graphid: row.GMP ? row.GMP : '', //GMP
          printMode: this.formData.printMode, //打印模式
          sortNum: this.formData.sortNum, //容器号
          supplierCode: row.sender_type ? row.sender_type : '', //供应商代码
          beforePrintFlag: '0', //不是期初打印,
          finallyCode: this.formData.finallyCode //到底映射的什么
        };
      },
      // 关闭标签打印期框
      handleClose() {
        this.dialogVisible = false;
        this.$nextTick(() => {
          this.$refs.elForm.resetFields(); // 重置表单
        });
      },
      //打印
      submitPrint() {
        this.$refs.elForm.validate((valid) => {
          if (!valid) {
            return; // 验证不通过直接返回
          }
          this.$refs.buyIndexRef.printCode(this.formData.temp, this.formData, 'late');
          this.dialogVisible = false;
        })
      },
      //格式化时间
      formatDate(date) {
        if (!date) return ''; // 如果 `date` 为空或 `null`，返回占位符
        return this.$dayjs(date).isValid() ? this.$dayjs(date).format('YYYY-MM-DD') : '-';
      },
      //改变商品状态
      verifyOrgChange(val) {
        this.queryGoodsList.skuStateValue = val;
        if (val == '') {
          this.queryGoodsList.skuStateValue = 0;
        } else {
          this.queryGoodsList.skuStateValue = 1;
        }
        this.getGoods();
      },
      //查看&解冻
      queryFrozen(row) {
        this.queryVisible = true;
        this.$refs.queryVisibleRef.openDialog(row);
      },
      //分页
      handleSizeChange(newsize) {
        this.pageNum = 1;
        this.pageSize = newsize;
      },
      handleCurrentChange(newpage) {
        this.pageNum = newpage;
      },
      //冻结
      frozen(row) {
        this.frozenDialogVisible = true;
        this.$refs.frozenDialogRef.openDiolog(row);
      },
      //状态
      stateBtn(row) {
        this.visibleForzen = true;
        this.$refs.frozenOperationRef.openDiolog(row);
      },
      //修改
      editFrozen(row) {
        this.visible = true;
        this.$refs.editFrozenRef.openDiolog(row);
      },
      /**
       * 远程搜索函数
       * 获取NCC物料信息
       */
      // 远程搜索函数 获取NCC物料信息
      searchSelectNccMaterial(query) {
        if (query !== '') {
          this.loading = true; // 开始加载
          const params = {
            materialName: query, // 传入输入的关键字
            modeCode:this.queryGoodsList.modeCode
          };
          // 调用接口进行物料信息查询
          getSelectNccMaterialInfo(params)
            .then(response => {
              if (response.code === 200) {
                // 更新物料选项
                this.materialNameOptions = response.data.map(item => ({
                  code: item.value, // 物料主键
                  name: item.label, // 物料名称
                }));
              } else {
                this.materialNameOptions = [];
              }
            })
            .catch(error => {
              console.error('查询物料信息失败:', error);
              this.materialNameOptions = [];
            })
            .finally(() => {
              this.loading = false; // 停止加载
            });
        } else {
          this.materialNameOptions = [];
        }
      },
      //获取商品状态下拉
      getGoodsState() {
        getBillStatusAll().then(res => {
          this.stateList = res.data;
        })
      },
      //查询
      getGoodsQuery() {
        this.getGoods();
      },
      getGoods() {
        let param = {
          skuID: this.queryGoodsList.materialName,
          batchNoValue: this.batchNoMode,
          batchNo: this.queryGoodsList.node,
          skuState: this.queryGoodsList.skuState,
          skuStateValue: this.queryGoodsList.skuStateValue,
          skuIDValue: this.queryGoodsList.materialName ? 1 : 0,
          wareHouseID: this.queryGoodsList.wareHouseID.join(','),
          wareHouseValue: this.queryGoodsList.wareHouseValue,
          // skuState:this.queryGoodsList.skuState
        }
        getWarehouseStatistic(param).then(res => {
          this.goodsList = res.data.type4 || [];
          this.total = res.data.type4.length;
        })
      },
      //下拉菜单
      handleCommand(command) {
        if (command == 0) {
          this.batchNoMode = command;
          this.btnTXT = '全部';
          this.getGoodsQuery();
        } else if (command == 1) {
          this.batchNoMode = command;
          this.btnTXT = '等于';
          this.getGoodsQuery();
        } else if (command == 2) {
          this.batchNoMode = command;
          this.btnTXT = '不等于';
          this.getGoodsQuery();
        } else if (command == 3) {
          this.batchNoMode = command;
          this.btnTXT = '包含';
          this.getGoodsQuery();
        } else {
          this.batchNoMode = command;
          this.btnTXT = '不包含';
          this.getGoodsQuery();
        }
      },
      clearAll() {
        this.queryGoodsList.materialName = '';
        this.queryGoodsList.node = '';
        this.queryGoodsList.skuState = '';
        this.queryGoodsList.skuStateValue = 0;
        this.btnTXT = '等于';
        this.batchNoMode = 1;
        this.getGoodsQuery();
      }
    }
  }
</script>

<style scoped lang="scss">
  .app-container {
    padding: 20px;
  }

  .el-card {
    margin-bottom: 20px;
  }

  .el-pagination {
    float: right;
    margin: 20px;
  }
</style>
